﻿using ciji.Core;
using Furion;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace ciji.Application.Data
{
 
    /// <summary>
    /// 文件管理
    /// </summary>
    [ApiDescriptionSettings("文件管理", Order = 600, Description = "文件管理")]
    public class FileService : IDynamicApiController
    {

        private static string DiskPath = App.Configuration["FileConfig:DiskPath"];
        private static string FileOutUrl = App.Configuration["FileConfig:OutUrl"];
        private static string bucketName = App.Configuration["FileConfig:bucketName"];
        private SqlSugarRepository<cts_DBInfo> _dbInfoRep;
        private SqlSugarRepository<cts_DBInfoImg> _dbInfoImgRep;
        private SqlSugarRepository<cts_JZInfo> _jzInfoRep;
        private SqlSugarRepository<cts_JZInfoImg> _jzInfoImgRep;
        private SqlSugarRepository<cts_AssessOrgImg> _assessOrgImgRep;
        private SqlSugarRepository<cts_OrgAssessBedImg> _bedImgRep;
        private SqlSugarRepository<cts_OrgAssessServiceImg> _orgServiceImgRep;
        private SqlSugarRepository<cts_OrgAssessServiceBasicImg> _orgBasicImgRep;
        private SqlSugarRepository<cts_OrgAssessSafeImg> _orgSafeImgRep;
        
        private SqlSugarRepository<cts_RijianAssessImg> _rijianAssessImgRep;
        private SqlSugarRepository<cts_XFYAssessImg> _xfyAssessImgRep;



        public FileService(SqlSugarRepository<cts_DBInfo> dbInfoRep
            , SqlSugarRepository<cts_DBInfoImg> dbInfoImgRep
            , SqlSugarRepository<cts_JZInfo> jzInfoRep
            , SqlSugarRepository<cts_JZInfoImg> jzInfoImgRep
            , SqlSugarRepository<cts_AssessOrgImg> assessOrgImgRep
            , SqlSugarRepository<cts_OrgAssessBedImg> bedImgRep
            , SqlSugarRepository<cts_OrgAssessServiceImg> orgServiceImgRep
            , SqlSugarRepository<cts_OrgAssessServiceBasicImg> orgBasicImgRep
            ,  SqlSugarRepository<cts_OrgAssessSafeImg> orgSafeImgRep
            , SqlSugarRepository<cts_RijianAssessImg> rijianAssessImgRep
            , SqlSugarRepository<cts_XFYAssessImg> xfyAssessImgRep)
        {
            _dbInfoRep = dbInfoRep;
            _dbInfoImgRep = dbInfoImgRep;
            _jzInfoRep = jzInfoRep;
            _jzInfoImgRep = jzInfoImgRep;
            _assessOrgImgRep = assessOrgImgRep;
            _orgServiceImgRep = orgServiceImgRep;
            _orgBasicImgRep = orgBasicImgRep;
            _orgSafeImgRep = orgSafeImgRep;
            _bedImgRep = bedImgRep;

            _rijianAssessImgRep = rijianAssessImgRep;
            _xfyAssessImgRep = xfyAssessImgRep;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>  
        [HttpPost]
        public async Task<dynamic> UploadFile(IFormFile file,[FromForm] string name)
        {
            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }
             
            if (string.IsNullOrEmpty(name))
            {
                name = "file";
            }
            name = name.Replace(" ", "");
            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName);
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/files/{now.Year}/{now.Month}/{name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            var rst = new
            {
                name = fileName,
                extname = extension,
                Url = FileOutUrl + linkPath

            };
            return rst;

        }


        /// <summary>
        /// 上传图片
        /// </summary>     
        /// <returns></returns> 
        [HttpPost]
        public async Task<string> UploadImg(IFormFile file, [FromForm] string name)
        {

            if (string.IsNullOrEmpty(name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            name = name.Replace(" ", "");
            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName);
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgyanglao/{now.Year}/{now.Month}/{name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return FileOutUrl + linkPath; 
        }

        /// <summary>
        /// 上传图片
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic> DBUploadImg(IFormFile file, [FromForm] string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            name = name.Replace(" ", "");
            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName);
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgyanglao/{now.Year}/{now.Month}/{name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return FileOutUrl + linkPath;

        }


        /// <summary>
        /// 上传录音
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<string> DBUploadRecording(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("录音文件不能为空");
            } 
           
            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            desc.name = desc.name.Replace(" ", "");

            var fileName = file.FileName; 
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgdibao/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            } 
            var path = FileOutUrl + linkPath; 
            _dbInfoRep.AsUpdateable().SetColumns(m => new cts_DBInfo
            {
                SoundRecording=path,
                RecordingTime=desc.recordingtime

            }).Where(m => m.Gid == desc.gid).ExecuteCommand();
             
            return path;

        }

        /// <summary>
        /// 上传图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<cts_DBInfoImg> DBUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("录音文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            desc.name = desc.name.Replace(" ", "");
         

            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName+= ".mp4";
                }
                else
                {
                    fileName+= ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgdibao/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath; 

            cts_DBInfoImg item = new cts_DBInfoImg
            {
                Gid = Guid.NewGuid().ToString(),
                DBInfoId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now, 
                ImgUrl = path
            };
            _dbInfoImgRep.Insert(item);
            return item; 

        }


       


        /// <summary>
        /// 上传图片
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<dynamic> JZUploadImg(IFormFile file, [FromForm] string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            name = name.Replace(" ", "");
            var fileName = file.FileName;
            var extension = Path.GetExtension(fileName);
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgyanglao/{now.Year}/{now.Month}/{name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return FileOutUrl + linkPath;

        }


        /// <summary>
        /// 上传录音
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<string> JZUploadRecording(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("录音文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            desc.name = desc.name.Replace(" ", "");

            var fileName = file.FileName;
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgdibao/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;
            _jzInfoRep.AsUpdateable().SetColumns(m => new cts_JZInfo
            {
                SoundRecording = path,
                RecordingTime = desc.recordingtime

            }).Where(m => m.Gid == desc.gid).ExecuteCommand();

            return path;

        }

        /// <summary>
        /// 上传图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<cts_JZInfoImg> JZUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("人员姓名不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgdibao/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            cts_JZInfoImg item = new cts_JZInfoImg
            {
                Gid = Guid.NewGuid().ToString(),
                DBInfoId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now,
                ImgUrl = path
            };
            _jzInfoImgRep.Insert(item);
            return item;

        }


        /// <summary>
        /// 上传图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<cts_AssessOrgImg> OrgUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {


            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("机构不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgorg/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            cts_AssessOrgImg item = new cts_AssessOrgImg
            {
                Gid = Guid.NewGuid().ToString(),
                OrgItemId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now,
                ImgUrl = path
            };
            _assessOrgImgRep.Insert(item);
            return item;


        }



        public async Task<dynamic> OrgUploadImgSaveInfoByType(IFormFile file, [FromForm] DBUploadInput desc)
        {


            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("机构不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgorg/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            if (desc.type == ItemImgType.ItemImgOrgService)
            {
                cts_OrgAssessServiceImg item = new cts_OrgAssessServiceImg
                {
                    Gid = Guid.NewGuid().ToString(),
                    OrgItemId = desc.gid,
                    Type = desc.imgtype,
                    sys_CreateDate = DateTime.Now,
                    ImgUrl = path
                };
                _orgServiceImgRep.Insert(item);
                return item;

            }
            else if (desc.type == ItemImgType.ItemImgOrgServiceBasic)
            {
                cts_OrgAssessServiceBasicImg item = new cts_OrgAssessServiceBasicImg
                {
                    Gid = Guid.NewGuid().ToString(),
                    OrgItemId = desc.gid,
                    Type = desc.imgtype,
                    sys_CreateDate = DateTime.Now,
                    ImgUrl = path
                };
                _orgBasicImgRep.Insert(item);
                return item;
            }

            else if (desc.type == ItemImgType.ItemImgOrgSafe)
            {
                cts_OrgAssessSafeImg item = new cts_OrgAssessSafeImg
                {
                    Gid = Guid.NewGuid().ToString(),
                    OrgItemId = desc.gid,
                    Type = desc.imgtype,
                    sys_CreateDate = DateTime.Now,
                    ImgUrl = path
                };
                _orgSafeImgRep.Insert(item);
                return item;
            }
            return null; 


        }





        /// <summary>
        /// 机构上传床位评定图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public async Task<cts_OrgAssessBedImg> OrgBedUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {

            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("机构不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgorg/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            cts_OrgAssessBedImg item = new cts_OrgAssessBedImg
            {
                Gid = Guid.NewGuid().ToString(),
                OrgItemId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now,
                ImgUrl = path
            };
            _bedImgRep.Insert(item);
            return item;



        }


        /// <summary>
        /// 日间上传床位评定图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>

        public async Task<cts_RijianAssessImg> RijianUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("机构不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgorg/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            cts_RijianAssessImg item = new cts_RijianAssessImg
            {
                Gid = Guid.NewGuid().ToString(),
                OrgItemId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now,
                ImgUrl = path
            };
            _rijianAssessImgRep.Insert(item);
            return item;


        }

        /// <summary>
        /// 幸福院上传床位评定图片、视频 保存信息
        /// </summary>     
        /// <returns></returns>

        public async Task<cts_XFYAssessImg> XFYUploadImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {
            if (file == null)
            {
                throw Oops.Bah("上传文件不能为空");
            }

            if (string.IsNullOrEmpty(desc.name))
            {
                throw Oops.Bah("机构不能为空");
            }
            desc.name = desc.name.Replace(" ", "");


            var fileName = file.FileName;
            string extname = Path.GetExtension(fileName);
            if (string.IsNullOrEmpty(extname))
            {
                if (desc.imgtype == 9)
                {
                    fileName += ".mp4";
                }
                else
                {
                    fileName += ".jpeg";
                }
            }

            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgorg/{now.Year}/{now.Month}/{desc.name}/{Guid.NewGuid().ToString()}";
            var savePath = Path.Combine(DiskPath, dicPath);

            var linkPath = Path.Combine(dicPath, fileName);
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var path = FileOutUrl + linkPath;

            cts_XFYAssessImg item = new cts_XFYAssessImg
            {
                Gid = Guid.NewGuid().ToString(),
                OrgItemId = desc.gid,
                Type = desc.imgtype,
                sys_CreateDate = DateTime.Now,
                ImgUrl = path
            };
            _xfyAssessImgRep.Insert(item);
            return item;


        }




        /// <summary>
        /// 通用上传图片、视频 保存信息
        /// </summary>
        /// <param name="file"></param>
        /// <param name="desc"></param>
        /// <returns></returns>
        [HttpPost]
        public dynamic UploadItemImgSaveInfo(IFormFile file, [FromForm] DBUploadInput desc)
        {

            if (desc.type == ItemImgType.ItemImgOrg)
            {
                return OrgUploadImgSaveInfo(file, desc);
            }
            else if (desc.type == ItemImgType.ItemImgOrgBed)
            {
                return OrgBedUploadImgSaveInfo(file, desc);
            }
            else if (desc.type == ItemImgType.ItemImgXFY)
            {
                return XFYUploadImgSaveInfo(file, desc);
            }
            else if (desc.type == ItemImgType.ItemImgRijian)
            {
                return RijianUploadImgSaveInfo(file, desc);
            }
            else
            {
                return OrgUploadImgSaveInfoByType(file, desc);
            }




        }
    }
}
